package com.cmcc.passenger.ui.onorder

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.os.CountDownTimer
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.alibaba.android.arouter.facade.annotation.Route
import com.cmcc.passenger.R
import com.cmcc.passenger.config.AppConfig
import com.cmcc.passenger.config.AppConfig.ICON_FILE_URL
import com.cmcc.passenger.config.PassPath
import com.cmcc.passenger.data.entity.response.NearbyCar
import com.cmcc.passenger.databinding.ActivityCarNearbyBinding
import com.cmcc.passenger.ui.base.BasicActivity

import com.cmcc.passenger.util.LocationUtil
import com.cmcc.shared.utils.L

import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.*
import java.io.IOException
import java.net.URL
import java.net.URLConnection
import java.text.SimpleDateFormat
import java.util.*


@Route(path = PassPath.CAR_NEARBY)
class CarNearByActivity : BasicActivity(), OnMapReadyCallback {


    private lateinit var viewModel: CarNearbyViewModel
    private lateinit var mMap: GoogleMap
    private var mapFragment: SupportMapFragment? = null
    val nearbyCar = MutableLiveData<List<NearbyCar>>()
    private lateinit var binding: ActivityCarNearbyBinding


    override fun onMapReady(googleMap: GoogleMap) {

        mMap = googleMap

        val appointLoc = LocationUtil.getInstance().getCurrentLoc()

        googleMap?.moveCamera(CameraUpdateFactory.newLatLngZoom(appointLoc, 18f))

    }


    override fun initialize(savedInstanceState: Bundle?) {

        viewModel = ViewModelProviders.of(this).get(CarNearbyViewModel::class.java)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_car_nearby)

        mapFragment = supportFragmentManager
            .findFragmentById(R.id.map) as SupportMapFragment?
        mapFragment?.getMapAsync(this)

        binding.toolbar.title.text = getString(R.string.nearby_car_title)


        binding.toolbar.toolbar.setNavigationOnClickListener { finish() }

        val x = intent.getDoubleExtra("x", 0.0)
        val y = intent.getDoubleExtra("y", 0.0)

        viewModel.getNearbyDriver(y, x)



//               val createTime = intent.getStringExtra("createTime")
//
//        var createDate: Date =
//            SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(createTime)
//
//        var nowTime = Date()
//        var timeGap = (nowTime.time - createDate.time) / 1000
//
//        if (timeGap > 180) {
//            finish()
//        } else {
//            val mCountDownTimer =
//                object : CountDownTimer(createDate.time + 181 * 1000 - nowTime.time, 1000) {
//                    override fun onTick(millisUntilFinished: Long) {
//
//                    }
//
//                    override fun onFinish() {
//                        finish()
//                    }
//                }
//            mCountDownTimer.start()
//        }

    }

    override fun initView(savedInstanceState: Bundle?) {
        val startAddress = intent.getStringExtra("startAddress")
        val endAddress = intent.getStringExtra("endAddress")
        binding.directionStart.text = startAddress
        binding.directionEnd.text = endAddress
    }


    override fun initObserver(savedInstanceState: Bundle?) {
        viewModel.nearbyCar.observe(this, Observer { cars ->

            var latLngList: MutableList<LatLng> = ArrayList()
            for (car in cars) {
                latLngList.add(LatLng(car.currentCoordinates.y, car.currentCoordinates.x))

                val navigationIconFilePath = AppConfig.FILE_URL.plus("icon/").plus("ic_".plus(car.driverCar.vehicleTypeCode).plus("_nav.png"))
                drawMarker(car, navigationIconFilePath)
            }
            zoomRoute(latLngList)
        })




    }



    private fun drawMarker(car: NearbyCar, urlPath: String) {
        Thread {
            try {
                val url = URL(urlPath)
                var conn: URLConnection? = null
                conn = url.openConnection()
                conn?.connect()
                val inputStream = conn?.getInputStream()
                val bitmap = BitmapFactory.decodeStream(inputStream)

                runOnUiThread {
                    mMap?.addMarker(
                        MarkerOptions().position(
                            LatLng(
                                car.currentCoordinates.y,
                                car.currentCoordinates.x
                            )
                        ).icon(BitmapDescriptorFactory.fromBitmap(bitmap))
                    )
                }

            } catch (e: IOException) {
                e.printStackTrace();
            }
        }.start()
    }


    /**
     * Zooms a Route (given a List of LalLng) at the greatest possible zoom level.
     *
     * @param googleMap: instance of GoogleMap
     * @param lstLatLngRoute: list of LatLng forming Route
     */
    private fun zoomRoute(lstLatLngRoute: List<LatLng>?) {

        if (mMap == null || lstLatLngRoute == null || lstLatLngRoute.isEmpty()) return;

        val boundsBuilder = LatLngBounds.Builder()
        for (latLngPoint in lstLatLngRoute)
            boundsBuilder.include(latLngPoint)

        val routePadding = 100
        val latLngBounds = boundsBuilder.build()

        mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds, routePadding));
    }
}